<template>
  <div class="list-common-table">
    <t-dialog :visible="modiVisible && !manager" @close="()=>{modiVisible=false;modiInfo=modiClearInfo}"
      @cancel="()=>{modiVisible=false;modiInfo=modiClearInfo}" size="80%" @confirm="postRecheckOrder">
      <t-select v-model="modiInfo.PID" placeholder="请选择患者" clearable>
        <t-option v-for="item in patients" :value="item.PID" :label="item.name+' (' + item.PID.slice(5,10)+')'"
          :key="item.PID">
        </t-option>
      </t-select>
      <t-date-picker theme="primary" mode="date" clearable v-model="modiInfo.checkTime"></t-date-picker>
      <t-card>
        <t-button @click="()=>{showModiAdd=true}" v-show="!showModiAdd">新加检查项目</t-button>
        <t-input v-show="showModiAdd" v-model="tempString"></t-input>
        <t-button v-show="showModiAdd" theme="default" @click="showModiAdd=false;tempString=''">取消</t-button>
        <t-button v-show="showModiAdd" theme="primary"
          @click="modiInfo.checkList.push(tempString);tempString='',showModiAdd=false">添加</t-button>
        <t-list :split="true" size="small">
          <t-list-item v-for="(item,index) in modiInfo.checkList">
            <t-list-item-meta :title="item"></t-list-item-meta>
          </t-list-item>
        </t-list>
      </t-card>
      <t-switch v-model="addSF36"></t-switch>添加SF36问卷
    </t-dialog>

    <t-dialog :visible="modiCheckVisible && !manager" @close="()=>{modiCheckVisible=false;modiInfo=modiClearInfo}"
      @cancel="()=>{modiCheckVisible=false;modiInfo=modiClearInfo}" size="80%" @confirm="postRecheckMemo">
      <t-select v-model="modiInfo.PID" placeholder="请选择患者" clearable>
        <t-option v-for="item in patients" :value="item.PID" :label="item.name+' (' + item.PID.slice(5,10)+')'"
          :key="item.PID">
        </t-option>
      </t-select>
      <t-date-picker theme="primary" mode="date" clearable v-model="modiInfo.checkTime"></t-date-picker>
      <t-card>
        <t-button @click="()=>{showModiAdd=true}" v-show="!showModiAdd">新加检查结果</t-button>
        <t-input v-show="showModiAdd" v-model="tempString" placeholder="复查项目"></t-input>
        <t-input v-show="showModiAdd" v-model="tempString2" placeholder="复查结果"></t-input>
        <t-button v-show="showModiAdd" theme="default" @click="showModiAdd=false;tempString='';tempString2=''">取消
        </t-button>
        <t-button v-show="showModiAdd" theme="primary"
          @click="modiInfo.checkList.push({title:tempString,info:tempString2});tempString='',showModiAdd=false">添加
        </t-button>
        <t-list :split="true" size="small">
          <t-list-item v-for="(item,index) in modiInfo.checkList">
            <t-list-item-meta :title="item.title" :description="item.info"></t-list-item-meta>
          </t-list-item>
        </t-list>
      </t-card>
    </t-dialog>

    <t-form ref="form" :data="formData" :label-width="80" colon @reset="onReset" @submit="onSubmit">
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[16, 16]">
            <t-col :flex="1" v-show="!manager">
              <t-button @click="()=>{modiVisible=true}">提交复查提醒</t-button>
              <t-button @click="()=>{modiCheckVisible=true}">提交复查结果</t-button>
            </t-col>
            <t-col :flex="1">
              <t-form-item label="患者姓名" name="name">
                <t-select v-model="formData.PID" placeholder="请选择患者">
                  <t-option v-for="item in patients" :value="item.PID"
                    :label="item.name+' (' + item.PID.slice(5,10)+')'" :key="item.PID">
                  </t-option>
                </t-select>
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: '8px' }">查询</t-button>
          <t-button type="reset" variant="base" theme="default">重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <div class="table-container">
      <t-table :data="data" :columns="columns" :rowKey="rowKey" :stripe="defaultTrue" :verticalAlign="verticalAlign"
        :hover="hover" :pagination="pagination" @page-change="rehandlePageChange" @change="rehandleChange"
        :loading="dataLoading">
        <template #op="slotProps">
        </template>
      </t-table>
    </div>
  </div>
</template>

<script>
  import {
    prefix
  } from '@/config/global';
  // import Trend from '@/components/trend/index.vue';
  // import Card from '@/components/card/index.vue';
  // import Editor from '@tinymce/tinymce-vue'
  import {
    ARTICLE_STATUS,
    ARTICLE_STATUS_OPTIONS,
    ARTICLE_TYPE_OPTIONS
  } from '@/constants';
  import tcb from "tcb-js-sdk"
  let tcbApp = tcb.init({
    env: "test-8gnvuow8188ceb83"
  })
  let auth = tcb.auth();
  auth.anonymousAuthProvider().signIn() // 匿名登录，实际业务时根据需要进行调整
    .then(() => {
      console.log("登陆成功") //登录成功
    }).catch(err => {
      console.log("登录失败", err) //登录失败
    })
  export default {
    name: 'list-table',
    components: {
      // 'editor': Editor
    },
    data() {
      return {
        tempString: '',
        tempString2: '',
        addSF36: false,
        showModiAdd: false,
        patients: [],
        selectedPatient: '',
        showReview: false,
        modiCheckVisible: false,
        modiVisible: false,
        modiInfo: {
          PID: '',
          checkList: [],
          name: "",
          checkTime: "",
        },
        modiClearInfo: {
          PID: '',
          checkList: [],
          name: "",
          checkTime: "",
        },
        manager: false,
        defaultTrue: true,
        workorderInfo: {},
        infoVisible: false,
        postVisible: false,
        postValue: '',
        ARTICLE_STATUS,
        ARTICLE_STATUS_OPTIONS,
        ARTICLE_TYPE_OPTIONS,
        prefix,
        formData: {
          PID: ''
        },
        data: [],
        dataLoading: false,
        value: 'first',
        columns: [{
            title: '患者姓名',
            width: 125,
            fixed: 'left',
            ellipsis: true,
            colKey: 'name'
          },
          {
            title: '(预期)检查时间',
            // minWidth: '300',
            align: 'left',
            // ellipsis: true,
            colKey: 'checkTime',
            width: 250
          },
          {
            title: '检查项目',
            // minWidth: '300',
            align: 'left',
            // ellipsis: true,
            colKey: 'checkListString',
            width: 250
          }
        ],
        rowKey: 'index',
        tableLayout: 'auto',
        verticalAlign: 'top',
        bordered: true,
        hover: true,
        rowClassName: rowKey => `${rowKey}-class`,
        // 与pagination对齐
        pagination: {
          defaultPageSize: 10,
          total: 100,
          defaultCurrent: 1,
          pageSizeOptions: [5, 10, 20, 50]
        },
        pages: {
          current: 1,
          pageSize: 10
        },
        confirmVisible: false,
        deleteIdx: -1,
      };
    },
    computed: {},
    mounted() {
      // console.log(this.$store.state.user.userInfo.type)
      if (localStorage.getItem('ovcf-token') != undefined) {
        console.log('set token');
        this.$store.commit('user/setToken', localStorage.getItem('ovcf-token'));
        this.$store.commit('user/setUserInfo', JSON.parse(localStorage.getItem('info')));
      }

      this.formData = {
        PID: ""
      }
      this.dataLoading = true;
      this.$request
        .post('/doctor-patient?type=recheckList&pageSize=10&current=1', this.formData)
        .then(res => {
          if (res.code === 0) {
            console.log(res);
            this.pagination.total = res.count;
            this.data = res.info;
            this.patients = res.patname
            for (let i = 0; i < this.data.length; i++) {
              let temp = ''
              if (this.data[i].checkList[0] == "sf36") {
                this.data[i].checkListString = "sf36"
                continue;
              }
              for (let j = 1; j < this.data[i].checkList.length; j++) {
                temp += this.data[i].checkList[j]
                temp += ' '
              }
              this.data[i].checkListString = temp
            }
          }
        })
        .catch(e => {
          this.$message.error('错误！');
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      this.manager = this.$store.state.user.userInfo.type === 'Doctor' ? false : true;
      for (let i = 0; i < this.data.length; i++) {
        this.data[i].content = this.data[i].content.replaceAll(/<[/s/S]*>/ig)
      }
    },
    methods: {
      postRecheckMemo() {
        if (this.modiInfo.checkTime == '') {
          this.$message.error("未填写日期")
          return
        }
        if (this.modiInfo.PID == '') {
          this.$message.error("未选择患者")
          return
        }
        if (this.modiInfo.checkList.length == 0) {
          this.$message.error("未添加项目")
          return
        }
        this.$request.post("/doctor-patient?type=postRecheckMemo", this.modiInfo)
          .then(res => {
            console.log(res)
            if (res.code == 0) {
              this.$message.success("成功！")
              this.modiCheckVisible = false;
              this.modiInfo = this.modiClearInfo
            } else {
              this.$message.error("失败！")
            }
          })
      },
      postRecheckOrder() {
        // console.log(this.modiInfo)
        if (this.modiInfo.checkTime == '') {
          this.$message.error("未填写日期")
          return
        }
        if (this.modiInfo.PID == '') {
          this.$message.error("未选择患者")
          return
        }
        for (let i = 0; i < this.patients.length; i++) {
          if (this.patients[i].PID == this.modiInfo.PID) {
            this.modiInfo.name = this.patients[i].name + ' (' + this.patients[i].PID.slice(5, 10) + ')'
          }
        }
        if (this.modiInfo.checkList.length == 0 && this.addSF36 == false) {
          this.$message.error("未添加项目")
          return
        } else if (this.modiInfo.checkList.length == 0 && this.addSF36 == true) {
          console.log("only sf36")
          this.modiInfo.checkList = ["sf36"]
          console.log(this.modiInfo)
          this.$request.post("/doctor-patient?type=postRecheckOrder", this.modiInfo).then(res => {
            console.log(res)
            if (res.code == 0) {
              this.$message.success("成功！")
              this.modiVisible = false;
              this.modiInfo = this.modiClearInfo
            } else {
              this.$message.error("失败！")
            }
          })
          return
        }
        for (let i = 0; i < this.patients.length; i++) {
          if (this.patients[i].PID == this.modiInfo.PID) {
            this.modiInfo.name = this.patients[i].name + ' (' + this.patients[i].PID.slice(5, 10) + ')'
          }
        }
        console.log("items")
        this.modiInfo.checkList.unshift("复查")
        console.log(this.modiInfo)
        this.$request.post("/doctor-patient?type=postRecheckOrder", this.modiInfo)
          .then(res => {
            console.log(res)
            if (res.code == 0) {
              this.$message.success("成功！")
              this.modiVisible = false;
              this.modiInfo = this.modiClearInfo
            } else {
              this.$message.error("失败！")
            }
          })
        if (this.addSF36 == true) {
          console.log("have sf36")
          this.modiInfo.checkList = ["sf36"]
          console.log(this.modiInfo)
          this.$request.post("/doctor-patient?type=postRecheckOrder", this.modiInfo)
            .then(res => {
              console.log(res)
              if (res.code == 0) {
                this.$message.success("成功！")
                this.modiVisible = false;
                this.modiInfo = this.modiClearInfo
              } else {
                this.$message.error("失败！")
              }
            })
        }
      },
      closeInfo() {
        this.infoVisible = false;
        this.postVisible = false;
        this.postValue = '';
        this.modiVisible = false;
        this.workorderInfo = {};
      },
      onReset(data) {
        console.log(data);
        this.formData.PID = ''
      },
      async onSubmit(data) {
        console.log(this.formData);
        // this.pagination.current = 1;
        this.$request
          .post('/doctor-patient?type=recheckList&pageSize=' + this.pages.pageSize + '&current=' + this.pages.current,
            this
            .formData)
          .then(res => {
            if (res.code === 0) {
              console.log(res);
              this.pagination.total = res.count;
              this.data = res.info;
              this.patients = res.patname
              for (let i = 0; i < this.data.length; i++) {
                let temp = ''
                if (this.data[i].checkList[0] == "sf36") {
                  this.data[i].checkListString = "sf36"
                  continue;
                }
                for (let j = 1; j < this.data[i].checkList.length; j++) {
                  temp += this.data[i].checkList[j]
                  temp += ' '
                }
                this.data[i].checkListString = temp
              }
            }
          })
          .catch(e => {
            console.log(e);
          })
          .finally(() => {
            this.dataLoading = false;
          });
      },
      async rehandlePageChange(curr, pageInfo) {
        console.log('分页变化', curr, pageInfo);
        this.pages.pageSize = curr.pageSize;
        this.pages.current = curr.current;
        await this.onSubmit();
      },
      rehandleChange(changeParams, triggerAndData) {
        console.log('统一Change', changeParams, triggerAndData);
      },
      rehandleClickOp({
        text,
        row
      }, type) {
        console.log(text, row, type);
      },
      handleClickDelete(row) {
        this.deleteIdx = row.rowIndex;
        this.confirmVisible = true;
      }
    }
  };
</script>
<style lang="less">
  @import './index.less';

  .list-common-table {
    background-color: @bg-color-container;
    padding: 30px 32px;
    border-radius: @border-radius;

    .table-container {
      margin-top: 30px;
    }
  }

  .form-item-content {
    width: 100%;
  }

  .operation-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .payment-col {
    display: flex;

    .trend-container {
      display: flex;
      align-items: center;
      margin-left: 8px;
    }
  }
</style>
